﻿using System;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows;
using SharpMap.Wpf;


namespace DragResizeRotateItems
{
    public class ResizeThumb : Thumb
    {
        private Point transformOrigin;
        private double angle;

        private Control parentItem;
        private Control ParentItem
        {
            get
            {
                if (parentItem == null)
                {
                    parentItem = this.DataContext as Control;
                }
                return parentItem;
            }
        }

        public ResizeThumb()
        {
            base.DragStarted += new DragStartedEventHandler(ResizeThumb_DragStarted);
            base.DragDelta += new DragDeltaEventHandler(ResizeThumb_DragDelta);
        }

        void ResizeThumb_DragStarted(object sender, DragStartedEventArgs e)
        {
            if (ParentItem != null)
            {
                transformOrigin = ParentItem.RenderTransformOrigin;

                RotateTransform rotateTransform = ParentItem.RenderTransform as RotateTransform;
                if (rotateTransform != null)
                    angle = rotateTransform.Angle * Math.PI / 180.0;   //convert degrees to radians
                else
                    angle = 0.0d;
            }
        }

        void ResizeThumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            if (ParentItem != null)
            {
                double deltaVertical, deltaHorizontal;
         
          
                deltaVertical = Math.Min(-e.VerticalChange, ParentItem.ActualHeight - ParentItem.MinHeight);
                Canvas.SetTop(ParentItem, Canvas.GetTop(ParentItem) + (transformOrigin.Y * deltaVertical * (1 - Math.Cos(-angle))));
                GeoPanel.SetViewY(ParentItem, GeoPanel.GetViewY(ParentItem) + (transformOrigin.Y * deltaVertical * (1 - Math.Cos(-angle))));
                
                
                Canvas.SetLeft(ParentItem, Canvas.GetLeft(ParentItem) );
                GeoPanel.SetViewX(ParentItem, GeoPanel.GetViewX(ParentItem) - deltaVertical * transformOrigin.Y * Math.Sin(-angle));
                ParentItem.Height -= deltaVertical;
                deltaHorizontal = Math.Min(e.HorizontalChange, ParentItem.ActualWidth - ParentItem.MinWidth);
                 ParentItem.Width -= deltaHorizontal;
            

   
      
                   
            
              
            }
            e.Handled = true;
        }
    }
}
